package com.example.forum_system.interceptor;

import com.example.forum_system.common.AppVar;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.interceptor
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-12  12:03
 * @Version : 1.0
 * @Description : TODO
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${bit-forum.login.url}")
    private String defaultURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session == null || session.getAttribute(AppVar.SESSION_USER)==null){
            log.error("用户没有会话，非法访问");
            if(!defaultURL.startsWith("/")){
                defaultURL = "/"+defaultURL;
            }
            response.sendRedirect(defaultURL);
            return false;
        }
        return true;
    }
}
